package edu.jmu.bean.system;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
/**
 * 菜单
 * @author Neal
 *
 */ 
@Entity
public class MenuNode implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1079202039325010751L;
	/**	主键	**/
	private Integer id;
	/**	名称	**/
	private String name;
	/**	节点的链接地址	**/
	private String url;
	/**	节点的显示位置	**/
	private int position;
	/**	节点的父亲节点	**/
	private MenuNode parentNode;
	/**	子节点	**/
	private List<MenuNode> childNodes = new LinkedList<MenuNode>();
		
	@Id	@GeneratedValue(strategy=GenerationType.AUTO)
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(length=20)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(length=50)
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}	
	@Column(precision=3)
	public int getPosition() {
		return position;
	}
	public void setPosition(int position) {
		this.position = position;
	}
	@ManyToOne(cascade=CascadeType.REFRESH)
	@JoinColumn(name="parentNode_id")
	public MenuNode getParentNode() {		
		return parentNode;
	}
	public void setParentNode(MenuNode parentNode) {
		this.parentNode = parentNode;
	}
	//@OneToMany(mappedBy="parentNode",cascade={CascadeType.REFRESH,CascadeType.REMOVE,CascadeType.PERSIST},fetch=FetchType.EAGER)
	@Transient
	public List<MenuNode> getChildNodes() {
		return childNodes;
	}
	public void setChildNodes(List<MenuNode> childNodes) {
		this.childNodes = childNodes;
	}
	
	/**
	 * 添加子节点 
	 * @param childNode 子节点 
	 */
	public void addChildNode(MenuNode childNode){
		childNode.setParentNode(this);
		this.childNodes.add(childNode);		
	}	
	
	/**
	 * 重写Hash，确保级联添加的时候没有添加重复节点
	 */
	@Override
	public int hashCode() {		
		return super.hashCode();
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		MenuNode other = (MenuNode) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}	
}
